package com.liangzong.betspider.service;

import com.liangzong.betspider.entity.TeamInfo;
import com.liangzong.betspider.entity.TeamPoint;
import com.liangzong.betspider.mapper.TeamInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Assert;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeamInfoService {
    @Autowired
    TeamInfoMapper teamInfoMapper;

    public void updateStateByUrl(List<String> collect) {
        teamInfoMapper.updateStateByUrl(collect);
    }

    //单线程执行 不会导致数据锁死
    @Transactional(rollbackFor = Throwable.class)
    public boolean addOrUpdate(TeamInfo teamInfo) {
        TeamInfo getTeam = teamInfoMapper.selectByPrimaryKey(teamInfo.getId());
        if (getTeam != null) {


            TeamInfo updateInfo = new TeamInfo();
            updateInfo.setId(teamInfo.getId());
            updateInfo.setUpdateTime(teamInfo.getUpdateTime());
            updateInfo.setTime(teamInfo.getTime());
            updateInfo.setRefresh_times(getTeam.getRefresh_times() + 1);

            if (getTeam.getAddTime() != null) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime addTime = getTeam.getAddTime();
                //如果是添加时间小于更新时间3小时，需要把添加时间更新，可能由于之前历史比赛记录会有脏数据
                if (addTime.plusHours(3).isBefore(now)) {
                    updateInfo.setAddTime(now);
                }
            }
            Assert.isTrue(teamInfoMapper.updateByPrimaryKeySelective(updateInfo) > 0, "更新比赛信息异常");
        } else {
            //保存
            Assert.isTrue(teamInfoMapper.insertSelective(teamInfo) > 0, "保存比赛信息异常");
        }
        return true;
    }

    public List<TeamInfo> query() {
        Example example = new Example(TeamInfo.class);
//        example.and().andEqualTo("state", 1).andGreaterThan("overTime", LocalDateTime.now());
        example.and().andEqualTo("state", 1).andGreaterThan("overTime", LocalDateTime.now());
        example.setOrderByClause("update_time desc");
        return teamInfoMapper.selectByExample(example);
    }

    public boolean update(TeamInfo teamInfo) {
        //更新
        teamInfoMapper.updateByPrimaryKeySelective(teamInfo);
        return true;
    }

}
